require Test::More;

use strict;
use Zim::Page;
use Zim::Selection;

$| = 1;
$SIG{__WARN__} = sub {
	print STDERR @_ unless $_[0] =~ /^\s*(Updating|Updated)\b/;
};

my $n = ':foo:bar:baz'; # start page
my $m = ':foo:test'; # moved page
my @p = # pages in repository
qw(
	:foo:aa
);
my %l = ( # moved pages
	':in'		=> ':out',
	':foo:bar:old'	=> ':foo:bar:new',
	':aa' 		=> ':bb',
);
my @l_resolve = ( # test resolve using Selection
	['dus' => ':foo:bar:dus'],
	[':out' => ':out'],
	['out' => ':out'],
	['bar:test' => ':foo:bar:test'],
	['foo:test:aa' => ':foo:test:aa'],
);
my @l_update = ( # links [link => updated]
	[':in' => 'out'],
	['in' => 'out'],
	['bar:old' => 'new'],
	['old' => 'new'],
	['aa' => 'aa'], # should resolve to :foo:aa not :aa
);
my @l_self = ( # links in moved page
	['dus' => 'foo:bar:dus'],
	[':in' => 'in'],
	['bar:test' => 'foo:bar:test'],
	['foo:test:aa' => 'test:aa'],
);
Test::More->import(tests => scalar @l_update + scalar @l_resolve + 5);

my $r = Zim::Selection->new(undef, {}, values %l, @p);
my $p = Zim::Page->new($r, $n);

is($p->name(), ':foo:bar:baz', 'name()');
is($p->namespace(), ':foo:bar:', 'namespace()');
is($p->basename(), 'baz', 'basename()');
is_deeply([$p->namespaces], ['foo', 'bar'], 'namespaces()');

#warn "Pages in selection: @{$r->{list}}\n";
for (@l_resolve) {
	my $name = $p->resolve_name($$_[0]);
	is($name, $$_[1], "Selection resolved $$_[0] => $$_[1]");
}

for (@l_update) {
	my ($old, $new) = @$_;
	$p->set_parse_tree(['Page', {}, ['link', {to => $old}, $old]]);
	$p->update_links(%l);
	is_deeply(
		$p->get_parse_tree(),
		['Page', {}, ['link', {to => $new}, $new], "\n"],
       		"update link $old => $new" );
}

my $old_tree = ['Page', {}, map ['link', {to => $_}, $_], map $$_[0], @l_self];
my $new_tree = ['Page', {}, map ['link', {to => $_}, $_], map $$_[1], @l_self];
push @$new_tree, "\n";
$p->set_parse_tree($old_tree);
$p->name($m); # move
$p->update_links_self($n);
is_deeply($p->get_parse_tree, $new_tree, 'update_links_self()');

